/*
 * Implement atoi to convert a string to an integer.
 * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
 * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
 */
#include <limits.h>
#include <string.h>
using namespace std;

class Solution {
public:
    int atoi(const char *str) {
        if (!str) {
            return 0;
        }
        int i = 0;
        while (str[i] == ' ') { i++; }
        int len = strlen(str);
        if (len == 0) {
            return 0;
        }
        bool neg = (str[i] == '-');
        i = (str[i] == '+' || str[i] == '-') ? (i+1) : i;
        int res = 0;
        for ( ; i < len; i++) {
            if (str[i] >= '0' && str[i] <= '9') {
                if (res > INT_MAX/10) {
                    if (neg) {
                        return INT_MIN;
                    } else {
                        return INT_MAX;
                    }
                }
                res *= 10;
                if (res > INT_MAX - (str[i] - '0')) {
                    if (neg) {
                        return INT_MIN;
                    } else {
                        return INT_MAX;
                    }
                }
                res += (str[i] - '0');
            } else {
                break;
            }
        }
        if (neg) {
            if (res == INT_MIN) {
                return 0;
            }
            return -res;
        }
        return res;
    }
};

int main() {
    return 0;
}
